<template>
    <div>
      <div class="course-info-div">

        <el-form ref="form" v-model="courseInfo" label-width="120px">
             <el-form-item label="课程URL：" style="width:650px;">
                <el-input disabled v-model="courseUrl"></el-input>

            </el-form-item>

            <el-form-item label="课程名称：" class="course-form-item">
                <el-input v-model="courseInfo.courseName"></el-input>

            </el-form-item>

            <el-form-item label="课程介绍：" class="course-form-item">
                <el-input
                type="textarea"
                :rows="3"
                
                placeholder="请输入内容："
                v-model="courseInfo.courseDesc">
                </el-input>
            </el-form-item>

            <el-form-item label="设置学期时间：" class="course-form-item">
                        <el-date-picker
                        v-model="time"
                        type="daterange"
                        value-format="yyyy-MM-dd HH:mm:ss"
                        range-separator="至"
                        start-placeholder="开始日期"
                        end-placeholder="结束日期">
                        </el-date-picker>
            </el-form-item>

        

            <el-form-item label="封面：">

                     <div v-show="!courseImgUpdate">

                        <div class="course-imgurl-div">

                        <img :src="courseInfo.courseImgUrl" class="avatar">
                        <!-- <i v-else class="el-icon-plus avatar-uploader-icon"></i> -->
                        <!-- </el-upload> -->
                        <el-button @click="updateImg" style="margin-left:1%;">修改</el-button>
                        </div>
                    </div>
                    
                    <div v-show="courseImgUpdate">

                        <div class="course-imgurl-div">
                            <el-upload
                            class="avatar-uploader"
                            action
                            :show-file-list="false"
                            v-model="courseInfo.courseImgUrl"
                            :before-upload="beforeAvatarUpload"
                            :http-request="getImgPutUrlFromSts"
                            >
                            <img v-if="uploadImgUrl" :src="uploadImgUrl" class="avatar">
                            <i v-else class="el-icon-plus avatar-uploader-icon"></i>
                            </el-upload>
    
                            <el-button style="margin-top: 8px;height:152px;margin-left:1%;" @click="updateImg">取消</el-button>
                        </div>

                        <el-tag type="info">请注意上传图片比例问题，请一定要让宽度 > 高度。最好比例为9：5</el-tag>
                    </div>


                   
            </el-form-item>
            

            <el-form-item label="修改班级：">
                <el-transfer v-model="courseInfo.classIds" :titles="['可选班级', '已选班级']"
                    :data="myClassInfo"></el-transfer>
             </el-form-item>

             <el-form-item>
                 <el-button type="primary" @click="updateCourseInfo">修改</el-button>
             </el-form-item>
        </el-form>

      </div>

  </div>
</template>

<script>
import * as COURSEAPI from '../../api/course/index'
import * as CLASSAPI from '../../api/class/index'
import * as FILEAPI from '../../api/file/index'
import UUID from 'uuidjs';

export default {
    props:['courseId'],
    data() {
        return {
            time:[],
            host:'',
            courseUrl:'',
            uploadImgUrl:'',
            urlPrefix:'',
            courseImgUpdate: false,
            courseInfo: {
                courseId:'',
                courseName: "",
                courseDesc: "",
                classIds: [],
                createTime: '',
                endTime:'',
                courseImgUrl:'',
                courseUrl:''
            },
            myClassInfo:[],
        }
    },
    methods:{
        getImgPutUrlFromSts(option) {
            let fileName = UUID.generate()
            let fileType = option.file.type.split("/")[1]
            FILEAPI.getImgUrl(fileName, fileType).then(res => {

                let url = res.data.URL

                const oReq = new XMLHttpRequest();
                oReq.open('PUT', url, true);
                oReq.setRequestHeader("Content-Type", "application/octet-stream")
                oReq.setRequestHeader("x-oss-meta-author", "nothing")
                oReq.send(option.file);
                oReq.onload = () => {
                    this.uploadImgUrl = `https://nothing-link.oss-cn-beijing.aliyuncs.com/${fileName}.${fileType}`;
                    this.courseInfo.courseImgUrl = `https://nothing-link.oss-cn-beijing.aliyuncs.com/${fileName}.${fileType}`;
                };
            }).catch((error) => {
                this.$notify.error({
                    title: '网路错误，或者服务器宕机',
                    message: error,
                });
            });
        },
        beforeAvatarUpload(file) {
            const isJPG = file.type === 'image/jpeg';
            const isPNG = file.type === 'image/png';
            const isLt2M = file.size / 1024 / 1024 < 2;

            if (!isJPG && !isPNG) {
                this.$message.error('上传头像图片只能是 JPG/PNG 格式!');
            }
            if (!isLt2M) {
                this.$message.error('上传头像图片大小不能超过 2MB!');
            }
            return (isJPG || isPNG) && isLt2M;
        },
        updateImg() {
            if (this.courseImgUpdate) this.courseImgUpdate = false
            else this.courseImgUpdate = true
        },
        getCourseInfo() {
            COURSEAPI.getCourseInfoById(this.courseId).then(res => {
                this.courseInfo = res.data.course
                this.time.push(this.courseInfo.createTime.replace("T", " "))
                this.time.push(this.courseInfo.endTime.replace("T", " "))
                this.courseUrl = this.urlPrefix + this.courseInfo.courseUrl
            })
        },
        getClassInfo() {
            CLASSAPI.getAllClassInfo(1, 2).then(res => {
            
                res.data.classInfos.forEach(classInfo => {
                    this.myClassInfo.push(
                            {
                                key:classInfo.classId,
                                label:classInfo.classRealName
                            }
                        )
                    });
            }).catch(err => {
                this.$message.error('网络错误！')
            })
        },
        updateCourseInfo() {
            for(let i = 0; i < this.time.length; i++) {
                if(i == 0) this.courseInfo.createTime = this.time[i]
                else this.courseInfo.endTime = this.time[i]

            }
            COURSEAPI.updateCourse(this.courseInfo).then(res => {
                if(res.code == 200) {
                    this.$notify({
                        title: '修改成功',
                        message: '这是一条成功的提示消息',
                        type: 'success'
                    });
                }else {
                    this.$notify.error({
                        title: '修改错误。',
                        message: error,
                    });
                }
            }).catch((error) => {
                this.$notify.error({
                    title: '网路错误，或者服务器宕机',
                    message: error,
                });
            });
        }
    },
    mounted() {
        let host = window.location.host;
        this.host = host
        this.urlPrefix = this.host + '/api/course/bind/'
        this.getCourseInfo()
        this.getClassInfo()
    }
}
</script>

<style>

.course-imgurl-div {
    display: flex;
    height: 152px;
    margin-bottom: 10px;
}

</style>